<template>
	<view>
		<h1>Todos</h1>
		<view class="add">
			<input type="text" v-model="title" placeholder="请输入待办事项" />
			<button size="mini" @click="sendFn">发布</button>
		</view>
		<view class="list">
			<view v-for="(item, index) in todos" :key="item.id">
				<switch :checked="item.completed" @change="changeCompleted(item.id,$event)" />
				{{ item.title }}
				<button size="mini" @click="delFn(item.id)">删除</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onMounted, ref } from 'vue';


const changeCompleted = (id,evt) => {
	const todo = todos.value.find(item => item.id ==id )
	todo.completed=evt.detail.value
		localStorage.setItem("todos", JSON.stringify(todos.value))
}


const delFn = (id) => {
	todos.value = todos.value.filter(item => item.id !== id)
	localStorage.setItem("todos", JSON.stringify(todos.value))
}


const todos = ref([])
const title = ref("")
const sendFn = () => {
	let id = new Date().getTime()
	todos.value.push({
		title: title.value,
		completed: false,
		id: id
	})
	localStorage.setItem("todos", JSON.stringify(todos.value))
	title.value = ""
}
onMounted(() => {
	getTodos()
})
const getTodos = () => {
	todos.value = JSON.parse(localStorage.getItem("todos"))
}
</script>

<style></style>
